/*********************************
* Vars
*********************************/
var req;	// XMLHttpRequest
var config;	// JSON Configuration
var list;	// Main list
var template;	// Table template
var weekday = new Array(7);	// Weekdays names
	weekday[0]="Sun";
	weekday[1]="Mon";
	weekday[2]="Tue";
	weekday[3]="Wed";
	weekday[4]="Thu";
	weekday[5]="Fri";
	weekday[6]="Sat";
// Constraint parameter and label
//      c filter expression is from configuration
//      = strict equality
//      n strict inequality
//      l like
//      ^ not like
//      ~ match
//      ! not match
var search_l = { 'c':"=", '=':"=", 'n':"\u2260", 'l':"\u2283", '^':"\u2285", '~':"~", '!':"\u2241" };
var search_h = { 'c':"Apply filter", '=':"Equal", 'n':"Not equal", 'l':"Match", '^':"Don't match", '~':"match regex", '!':"Don't match regex" };
	
/*********************************
* Add 0 digit
*********************************/
function format0(value,size) {
	var res = '0000' + value;
	return res.slice(res.length - size);
}

/*********************************
* Add logs (9=critical, 0=info)
*********************************/
function log( level, msg ) {
	var l = document.createElement("div");
	l.className = 'c_log';
	document.getElementById('logs_').appendChild(l);
	l.appendChild(document.createTextNode(msg));
}

/*********************************
* Clear logs
*********************************/
function clearlog() {
}

/*********************************
* Create a filter button
*********************************/
function ffilterbutton(baseNode,className,filterColumn,filterType,filterValueRaw) {
	var node = document.createElement('a');
	node.className = 'c_button ' + className;
	node.title = search_h[filterType];
	node.setAttribute('onclick','faddfilter("'+filterColumn+'","'+filterType+'",'+filterValueRaw+');fupdate();' );
	node.appendChild(document.createTextNode(search_l[filterType]));
	baseNode.appendChild(node);
}	

/*********************************
* Configuration at startup
*********************************/
function fconfig() {
	// Get configuration from config.json.php
	log(0,'Init');
	document.dynamic.offset = 0;
	req = new XMLHttpRequest();
	req.open("GET", "config.json.php", false); 
	req.send(null); 

	// Parse JSON data
        var jsonconfig = eval('(' + req.responseText + ')'); 
	config = jsonconfig.config;
	
	// Check format
	if (config.type != 'phpmysyslog-config' ) {
		log(9,'Error: invalid response\n(type='+config.type+')');
		return;
	}
	if (config.version != '1.0' ) {
		log(9,'Error: invalid response version\n(version='+config.version+')');
		return;
	}
	
	var base;			// Dom base node
	var node,node1,node2,node3;	// New nodes
	
	// Set ranges
	base = document.getElementById('ranges_');
	for (i=0; i<config.resets.length; i++) {
		node = document.createElement("a");
		node.className = 'c_button c_btn_time';
		node.title = config.resets[i].title;
		node.href = '#';
		//node.onclick = function() { setRange(config.resets[i].value); };
		node.setAttribute('onclick', 'setRange('+config.resets[i].value+'); fupdate();' );
		base.appendChild(node);
		node.appendChild(document.createTextNode(config.resets[i].label));
		base.appendChild(document.createTextNode('\u00a0\n'));
	}
	
	// Set number of line menu
	base = document.getElementById('Pmax');
	for (i=0; i<config.lines.length; i++) {
		node = document.createElement("option");
		node.value = config.lines[i];
		node.appendChild(document.createTextNode(config.lines[i]+' lines'));
		base.appendChild(node);
	}
	
	// Create Table header
	base = document.getElementById('main_head');
	for (i=0; i<config.item.length; i++) {
		node = document.createElement('th');
		node.className = 'c_sort';
		node.setAttribute('rel', config.item[i].name);
		node.appendChild(document.createTextNode(config.item[i].label));
		base.appendChild(node);
		base.appendChild(document.createTextNode('\n'));
	}
	
	// Create Table search line
	base = document.getElementById('main_search');
	for (i=0; i<config.item.length; i++) {
		// Header element
		node = document.createElement('th');
		node.className = 'c_search';
		base.appendChild(node);
		// span containning filters
		node1 = document.createElement('span');
		node1.className = 'c_filters';
		node1.id = config.item[i].name + '_param';
		node.appendChild(node1);
		// input for filtering
		switch (config.item[i].type) {
		
			// Create a "Update" button
			case 'TIMESTAMP':
				node1 = document.createElement('a');
				node.appendChild(node1);
				node1.className = 'reset';
				node2 = document.createElement('img');
				node2.id = 'update';
				node2.alt = 'update';
				node2.src = 'img/updating.gif';
				node1.appendChild(node2);
				node1.setAttribute('onclick', 'fupdate();' );
				break;
				
			// Create a fixed list
			case 'AUTOLIST':
			case 'LIST':
				node3 = document.createElement('div');
				node.appendChild(node3);
				// Create drop down list
				node1 = document.createElement('select');
				node3.appendChild(node1);
				node1.name = config.item[i].name;
				node1.id = config.item[i].name;
				// Add each value
				for (j=0; j<config.item[i].values.length; j++) {
					node2 = document.createElement('option');
					node1.appendChild(node2);
					node2.className = config.item[i].values[j].className;
					node2.value = config.item[i].values[j].name;
					node2.appendChild(document.createTextNode(config.item[i].values[j].label));
				}
				// Autolist
				if (config.item[i].type=='LIST') {
				// List
					ffilterbutton(node3,'c_btn_form',config.item[i].name,'c','document.dynamic.'+config.item[i].name+'.value')
				} else {
					// Add = and != buttons
					ffilterbutton(node3,'c_btn_form',config.item[i].name,'=','document.dynamic.'+config.item[i].name+'.value')
					ffilterbutton(node3,'c_btn_form',config.item[i].name,'n','document.dynamic.'+config.item[i].name+'.value')
				}
				break;
			
			// Partial, exact and regex match
			case 'PARTIALMATCH':
			case 'EXACTMATCH':
			case 'REGEXMATCH':
				// Help text	
/*				node1 = document.createElement('a');
				node.appendChild(node1);
				node1.className = 'help';
				node1.href = '#';
*/				// Input 
				node2 = document.createElement('input');
				node.appendChild(node2);
				node2.type = 'text';
				node2.name = config.item[i].name;
				node2.id = config.item[i].name;
				node2.size = config.item[i].size;
				node2.autocomplete = 'on';
				// Set help text and buttons
				if (config.item[i].type == 'PARTIALMATCH') {
/*					// Help
					node1.title = 'Partial match';
					node1.appendChild(document.createTextNode('%'));
*/					// Filter in
					ffilterbutton(node,'c_btn_form',config.item[i].name,'l','document.dynamic.'+config.item[i].name+'.value')
					// Filter out
					ffilterbutton(node,'c_btn_form',config.item[i].name,'^','document.dynamic.'+config.item[i].name+'.value')
				} else if (config.item[i].type == 'REGEXMATCH') {
/*					node1.title = 'Regex match';
					node1.appendChild(document.createTextNode('~'));
*/					// Filter in
					ffilterbutton(node,'c_btn_form',config.item[i].name,'~','document.dynamic.'+config.item[i].name+'.value')
					// Filter out
					ffilterbutton(node,'c_btn_form',config.item[i].name,'!','document.dynamic.'+config.item[i].name+'.value')

				} else {
/*					node1.title = 'Exact match';
					node1.appendChild(document.createTextNode('='));
*/					// Filter in
					ffilterbutton(node,'c_btn_form',config.item[i].name,'=','document.dynamic.'+config.item[i].name+'.value')
					// Filter out
					ffilterbutton(node,'c_btn_form',config.item[i].name,'n','document.dynamic.'+config.item[i].name+'.value')
				}
				break;
			
			// No search
			case 'TEXT':
				break;
				
			// Unknown value
			default:
				log(1,'Unknown type: '+config.item[i].type);
		}
		base.appendChild(document.createTextNode('\n'));
	}
	
	// Create template
	base = document.getElementById('main_template');
	for (i=0; i<config.item.length; i++) {
		node = document.createElement('td');
		node1 = document.createElement('div');
		node1.className = config.item[i].name + ' c_cell';
		node1.appendChild(document.createTextNode('-'));
		node.appendChild(node1);
		base.appendChild(node);
		base.appendChild(document.createTextNode('\n'));
	}

	// Create list item
	var listOptions = { 
		valueNames: [],
		//searchClass: '',, 
		listClass: 'c_main_body',
		item: 'main_template',
		sortClass: 'c_sort'
	};
	for (i=0; i<config.item.length; i++) {
		listOptions.valueNames.push(config.item[i].name);
	}
	list = new List('main',listOptions);
	log(0, 'Init.. done');
} 

/*********************************
* Update timestamp range search
*********************************/
function setRange(range) {
	// Init
	var enddate = new Date();	// End date = now
	var startdate = new Date(enddate.getTime() - (range*1000));
	var firstdate = new Date(config.start.slice(0,10));	// First value

	// Not before firstdate
	//alert( "firstdate=" + firstdate.getTime() + " ("+config.start.slice(0,10)+") startdate=" + startdate.getTime() );
	if ( firstdate.getTime() > startdate.getTime() ) {
		startdate = firstdate;
	}
	
	// More than a day => since 00:00:00
	if ( range > (24*60*60 + 1000) ) {
		startdate.setHours(0);
		startdate.setMinutes(0);
		startdate.setSeconds(0);
	}
	
	// Enddate 1 month in the futur
	enddate = new Date(enddate.getTime() + 1000*60*60*24*30);
	enddate.setHours(0);
	enddate.setMinutes(0);
	enddate.setSeconds(0);
	
	// Set values in form input's
	document.dynamic.Pstart_d.value = startdate.getFullYear() + '-' + format0(startdate.getMonth() + 1,2) + '-' + format0(startdate.getDate(),2);
	document.dynamic.Pstart_h.value = format0(startdate.getHours(),2) + ':' + format0(startdate.getMinutes(),2) + ':' + format0(startdate.getSeconds(),2);
	document.dynamic.Pend_d.value = enddate.getFullYear() + '-' + format0(enddate.getMonth() + 1,2) + '-' + format0(enddate.getDate(),2);
	document.dynamic.Pend_h.value = format0(enddate.getHours(),2) + ':' + format0(enddate.getMinutes(),2) + ':' + format0(enddate.getSeconds(),2);
	
	// Recalculate days
	setDayOfWeeks();
}

/*********************************
* Recalculate start_day and end_day
*********************************/
function setDayOfWeeks() {
	var startdate = new Date( document.dynamic.Pstart_d.value );
	document.getElementById('start_day').textContent = weekday[startdate.getDay()];
	var enddate = new Date( document.dynamic.Pend_d.value );
	document.getElementById('end_day').textContent = weekday[enddate.getDay()];
}

/*********************************
* Update content
*********************************/
function fupdate() {
	// Update indicator
	// Set parameters
	var param,base,node;
	//	Pmax, Poffset
	param = 'Pmax=' + encodeURIComponent(document.dynamic.Pmax.value) +
		'&Poffset=' + encodeURIComponent(document.dynamic.offset);
	
	//	Pstart_d & Pstart_h & Pend_d & Pend_h
	param += '&Pstart_d=' + encodeURIComponent(document.dynamic.Pstart_d.value) + 
		'&Pstart_h=' + encodeURIComponent(document.dynamic.Pstart_h.value) +
		'&Pend_d=' + encodeURIComponent(document.dynamic.Pend_d.value) +
		'&Pend_h=' + encodeURIComponent(document.dynamic.Pend_h.value);
	//	P$col
	for (i=0; i<config.item.length; i++) {
		base = document.getElementById(config.item[i].name + '_param');
		for (j=0; j<base.childNodes.length; j++) {
			param += '&'+config.item[i].name+j+'=' + encodeURIComponent( base.childNodes[j].type + base.childNodes[j].value );
		}
	}

	// Updating icon
	base = document.getElementById('update');
	base.alt = 'updating';
	base.src = 'img/updating.gif';
	
	// Get datas from request.json.php
	req = new XMLHttpRequest();
	req.open("POST", "request.json.php", true); 
	req.onreadystatechange = fupdate_json;
	req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	log( 0, "Req: "+param );
	req.send(param); 
}

/*********************************
* Parse JSON configuration
*********************************/
function fupdate_json() { 
	// Check status
	if (req.readyState != 4) {
		//alert('Error #'+ req.readyState + ' in XMLHttpRequest\n('+req.status+'/'+req.statusText+')');
		return;
	}
	// Parse JSON data
        var result = eval('(' + req.responseText + ')');
	log(0,'Loaded ('+decodeURIComponent(result.sql)+')');
	
	// Remove content
	var base = document.getElementById('main_body');
	while (base.lastChild != null) {
		base.removeChild(base.lastChild);
	}
	list.items = [];
	
	// Add content
	list.add(result.result);
	
	// More results?
	//if(
	
	// Add decoration
	var nodelist,node,node1,node2, node3;
	for (i=0;i<config.item.length;i++) {
		// Add class CSS only for LIST and AUTOLIST
		if (config.item[i].type == 'LIST' || config.item[i].type == 'AUTOLIST') {
			// For all element matching class='itemName'
			nodelist = ListJsHelpers.getByClass(config.item[i].name,document.getElementById('main_body'));
			for (j=0;j<nodelist.length;j++) {
				for (k=0;k<config.item[i].values.length;k++) {
					if (config.item[i].values[k].name==nodelist[j].textContent) {
						nodelist[j].className += ' ' + config.item[i].values[k].className;
					}
				}
			}
		}
	}

	// Add autofilter
	for (i=0;i<config.item.length;i++) {
		// Only on autofilter
		if (config.item[i].autofilter) {
			// For all element matching class='itemName'
			nodelist = ListJsHelpers.getByClass(config.item[i].name,document.getElementById('main_body'));
			for (j=0;j<nodelist.length;j++) {
				node = document.createElement('div');
				node.className = 'c_autof_abs';
				// Create "equal"
				ffilterbutton(node,'c_btn_autof',config.item[i].name,'=','"'+nodelist[j].textContent+'"')
				// Create "not equal"
				ffilterbutton(node,'c_btn_autof',config.item[i].name,'n','"'+nodelist[j].textContent+'"')
				nodelist[j].appendChild(node);
			}
		}
	}
	
	// Mask or show paging
	document.getElementById('Pyounger').style.visibility = ((document.dynamic.offset==0) ? 'hidden' : 'visible');
	document.getElementById('Polder').style.visibility = ((result.more) ? 'visible' : 'hidden');
	
	// Updating icon
	base = document.getElementById('update');
	base.alt = 'updating';
	base.src = 'img/update.gif';
}

/*********************************
* Add a filter
*********************************/
function faddfilter(column,type,value) {
	// Get the storage node
	var base = document.getElementById(column+'_param');
	// Add a div
	var node = document.createElement('div');
	node.className = 'c_param';
	node.type = type;
	node.value = value;
	// Add type
	var node1 = document.createElement('span');
	node1.className = 'c_prm_type';
	node1.appendChild(document.createTextNode(search_l[type]));
	node.appendChild(node1);
	// Add value
	node1 = document.createElement('span');
	node1.className = 'c_prm_val';
	node1.appendChild(document.createTextNode(value));
	node.appendChild(node1);
	// Spacer
	node.appendChild(document.createTextNode('\u00a0'));
	// Add remove button
	node1 = document.createElement('a');
	node1.className = 'c_button c_btn_remove';
	node1.setAttribute('onclick', 'fremove(this);fupdate();' );
	node1.appendChild(document.createTextNode('x'));
	node.appendChild(node1);
	base.parentNode.firstChild.appendChild(node,base);
}

/*********************************
* Remove a filter
*********************************/
function fremove(elem) {
	var base = elem.parentNode;
	base.parentNode.removeChild(base);
}

/*********************************
* Remove a filter
*********************************/
function fpaging(updown) {
	document.dynamic.offset += updown * document.dynamic.Pmax.value;
	if (document.dynamic.offset<0 ) {
		document.dynamic.offset = 0;
	}
	var base = document.getElementById('offset');
	base.removeChild(base.firstChild);
	base.appendChild(document.createTextNode(document.dynamic.offset));
}
